package com.systop.commer.controller;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 *
 *
 * @author chensh
 * @email 1508877606@qq.com
 * @date 2020-07-27 15:43:42
 */
@RestController
public class IoController {
    // <td width="10%"><img src="/imgshows?picName=${lists[i].phone_url}"/></td>
    //页面的读取文件方法
    @RequestMapping("/imgshows")
    public void picShow(HttpServletRequest request, HttpServletResponse response, String picName) throws IOException {
        picName=new String(picName.getBytes("ISO8859-1"),"UTF-8"); //防止中文乱码
// 本地地址
      // String filePath = "D:\\upload/upload/";
        //项目地址
       // String filePath = request.getSession().getServletContext().getRealPath("/uploads");
        String filePath = ClassUtils.getDefaultClassLoader().getResource("").getPath()+"static/uploads/";
        String imagePath =filePath+picName;
        response.reset();
        //判断文件是否存在
        File file = new File(imagePath);
        if (!file.exists()) {
            imagePath =filePath+picName;
        }
        // 得到输出流
        OutputStream output = response.getOutputStream();
        FileInputStream is = new FileInputStream(new File(imagePath));
        int i = is.available(); // 得到文件大小
        byte data[] = new byte[i];
        is.read(data); // 读数据
        is.close();
        response.setContentType("image/*"); // 设置返回的文件类型
        OutputStream toClient = response.getOutputStream(); // 得到向客户端输出二进制数据的对象
        toClient.write(data); // 输出数据
        toClient.close();
        output.close();
    }
}
